﻿Public Class Tileset
    Implements IDisposable
    Private mImage As Bitmap
    Private mTileSize As Size

#Region "IDisposable"
    Public Sub Dispose() Implements IDisposable.Dispose
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If mImage IsNot Nothing Then
                mImage.Dispose()
                mImage = Nothing
            End If
        End If
    End Sub
    Protected Overrides Sub Finalize()
        Dispose(False)
    End Sub
#End Region

    Public Sub New()
        mImage = New Bitmap(16, 16)
    End Sub

    Public Sub New(path As String)
        LoadTileSet(path)
    End Sub

    Public Sub LoadTileSet(path As String)
        Try
            mImage = CType(Drawing.Image.FromFile(path), Bitmap)
        Catch ex As Exception

        End Try
        mImage.MakeTransparent()
        mTileSize = New Size(mImage.Width \ 16, mImage.Height \ 16)
    End Sub

    Public Function GetTile(index As Integer) As Bitmap
        Dim col As Integer = index Mod 16
        Dim row As Integer = CInt(Math.Floor(index / 16))
        Return GetTile(col, row)
    End Function

    Public Function GetTile(col As Integer, row As Integer) As Bitmap
        Dim ret As New Bitmap(mTileSize.Width, mTileSize.Height, Imaging.PixelFormat.Format32bppArgb)
        Dim g As Graphics = Graphics.FromImage(ret)
        g.Clear(Color.Transparent)
        Dim srcRect As New Rectangle(col * mTileSize.Width, row * mTileSize.Height, mTileSize.Width, mTileSize.Height)
        g.DrawImage(mImage, New Rectangle(0, 0, mTileSize.Width, mTileSize.Height), srcRect, GraphicsUnit.Pixel)
        g.Dispose()
        Return ret
    End Function

    Public Function GetTile(chr As Char) As Bitmap
        Return GetTile(Asc(chr))
    End Function

    Public ReadOnly Property Image As Bitmap
        Get
            Return mImage
        End Get
    End Property

    Public ReadOnly Property TileSize As Size
        Get
            Return mTileSize
        End Get
    End Property
End Class
